import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import md5 from 'md5';
import moment from 'moment';
import { createToken } from '../auth.js';


const router = new Router;
router.prefix('/api');


router.post('/oper/login', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.account == null && body.openid == null) {
        ctx.body = response.fail("缺少必填字段 帐号或者openid");
        return;
    }
    if (body.openid != null) {
        let { count, rows } = await db.findAll('oper', { openid: body.openid }, null, 'desc', 1, 0, null, null);
        if (count == 0) {
            ctx.body = response.fail("帐号不存在");
            return;
        }
        let oper = rows[0];
        const { token, expireTime } = await createToken({ account: oper.account, permissonValue: oper.permissonValue });
        oper.token = token;
        oper.expireTime = expireTime;
        delete oper.password;
        ctx.body = response.success(rows[0]);
        return;
    }


    let { count, rows } = await db.findAll('oper', { account: body.account }, null, 'desc', 1, 0, null, null);
    if (count == 0) {
        ctx.body = response.fail("帐号不存在");
        return;
    }
    let oper = rows[0];
    if (oper.password == null) oper.password = '';
    if (oper.password == '' || oper.password == md5(body.password)) {
        const { token, expireTime } = await createToken({ account: oper.account, permissonValue: oper.permissonValue });
        oper.token = token;
        oper.expireTime = expireTime;
        delete oper.password;
        ctx.body = response.success(oper);
        return;
    }
    else {
        ctx.body = response.fail("密码错误");
    }
});



router.post('/oper/insert', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    let isExist = await db.findOne('oper', { account: body.account });
    if (isExist != null) {
        ctx.body = response.fail("相同帐号已存在");
        return;
    }
    if (body.password != null) {
        body.password = md5(body.password);
    }
    let res = await db.create('oper', body);
    if (res instanceof Error) {
        logger.error(`oper create error :` + res.message);
        ctx.body = response.fail(`oper create error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/oper/update', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail("缺少必填字段 帐号");
        return;
    }
    let obj = await db.findOne('oper', { account: body.account })
    if (obj == null) {
        ctx.body = response.fail("要修改数据不存在");
        return;
    }
    for (let key in body) {
        if (body[key] != undefined) {
            if (key == 'password') {
                obj[key] = md5(body[key]);
            }
            else {
                obj[key] = body[key];
            }
        }
    }
    let res = await db.update('oper', obj, { account: body.account });
    if (res instanceof Error) {
        logger.error(`oper update error :` + res.message);
        ctx.body = response.fail(`oper update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/oper/remove', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail("缺少必填字段 帐号");
        return;
    }
    let res = await db.deleteRow('oper', { account: body.account });
    if (res instanceof Error) {
        logger.error(`oper delete error :` + res.message);
        ctx.body = response.fail(`oper delete error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/oper/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' }
    }
    else {
        if (!body.direction) body.direction = 'desc';
    }
    let res = await db.findAll('oper', body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr, body.likeArr, body.leftJoinArr, body.inArr);
    console.log('res:', res);
    if (res instanceof Error) {
        logger.error(`oper getList error :` + res.message);
        ctx.body = response.fail(`oper getList error :` + res.message);
        return;
    }
    ctx.body = response.success({ rows: res.rows, count: res.count });
});

router.post('/oper/changePass', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail("缺少必填字段 帐号");
        return;
    }
    if (body.oldPass == null) {
        ctx.body = response.fail("缺少必填字段 旧密码");
        return;
    }
    if (body.newPass == null) {
        ctx.body = response.fail("缺少必填字段 新密码");
        return;
    }
    let oper = await db.findOne('oper', { account: body.account });
    if (oper == null) {
        ctx.body = response.fail("帐号不存在");
        return;
    }
    if (oper.password == '' || oper.password == md5(body.oldPass) || oper.password == null) {

        oper.password = md5(body.newPass);
        delete oper.permissonValue;
        let res = await db.update('oper', oper, { account: body.account });
        if (res instanceof Error) {
            logger.error(`oper update error :` + res.message);
            ctx.body = response.fail(`change password update error :` + res.message);
            return;
        }
        ctx.body = response.success();

    } else {
        ctx.body = response.fail("旧密码错误");
    }
});


router.post('/:table/insert', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    let isExist = false;
    switch (ctx.params.table) {
        case 'role':
            if (body.role_name == null) {
                ctx.body = response.fail("缺少必填字段 角色名称");
                return;
            }
            if (body.role_value == null) {
                ctx.body = response.fail("缺少必填字段 角色值");
                return;
            }
            isExist = await db.checkExist('role', { role_name: body.role_name });
            if (isExist) {
                ctx.body = response.fail("相同角色已存在");
                return;
            }
            break;
        case 'enterprise':
            if (body.enterpriseName == null) {
                ctx.body = response.fail("缺少必填字段 企业名称");
                return;
            }
            if (body.brand == null) {
                ctx.body = response.fail("缺少必填字段 品牌");
                return;
            }
            isExist = await db.checkExist('enterprise', { enterpriseName: body.enterpriseName });
            if (isExist) {
                ctx.body = response.fail("相同企业已存在");
                return;
            }
            break;


        default:
    }

    let res = await db.create(ctx.params.table, body);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} create error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} create error :` + res.message);
        return;
    }
    if (ctx.params.table == 'device') {
        memDB.setDevice({ sn: body.sn, model: body.model });
    }
    ctx.body = response.success({ id: res.insertId });
});

function getConditions(tbaleName, body) {
    let conditions = {};
    switch (tbaleName) {
        case 'enterprise':
            if (body.enterpriseName == null) {
                return { code: 0, conditions, msg: "缺少必填字段 enterpriseName" };
            }
            conditions = { enterpriseName: body.enterpriseName }
            return { code: 1, conditions: conditions };
        case `bicycle`:
            if (body.bicycleCode == null) {
                return { code: 0, conditions, msg: "缺少必填字段 车辆编号" };
            }
            conditions = { bicycleCode: body.bicycleCode }
            return { code: 1, conditions: conditions };

        default:
            if (body.id == null) {
                return { code: 0, conditions, msg: "缺少必填字段 id" };
            }
            conditions = { id: body.id }
            return { code: 1, conditions: conditions };

    }
}

router.post('/:table/update', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions
    let obj = await db.findOne(ctx.params.table, conditions)
    if (obj == null) {
        ctx.body = response.fail("要修改数据不存在");
        return;
    }
    for (let key in body) {
        if (body[key] != undefined && body[key] != null) {
            obj[key] = body[key];
        }
    }
    res = await db.update(ctx.params.table, obj, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} update error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/:table/remove', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions
    res = await db.deleteRow(ctx.params.table, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} delete error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} delete error :` + res.message);
        return;
    }
    if (ctx.params.table == 'device') {
        memDB.deleteDevice({ sn: body.sn });
    }
    ctx.body = response.success();
});
router.post('/:table/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' }
    }
    else {
        if (!body.direction) body.direction = 'desc';
    }
    //按分表查询数据
    if (ctx.params.table == 'orderinfo' || ctx.params.table == 'orderInfo') {
        if (body.areaArr == null|| body.areaArr.length==0) {
            ctx.params.table = `orderInfo_${moment().format('YYYYWW')}`;
        } else {
            // 检查条件区域里有 field 为 endTime 的字段时根据 start 和 end 时间来判断取分表的表名
            let index = body.areaArr.findIndex(item => item.field == 'endTime');
            // 开始时间取当前时间的周头
            let startDate = moment().startOf('week');
            let endDate = moment();
    
            if (index != -1) {
                startDate = moment(body.areaArr[index].start);
                endDate = moment(body.areaArr[index].end);
            }
    
            let weeks = [];
            while (startDate.isBefore(endDate) || startDate.isSame(endDate, 'week')) {
                weeks.push(startDate.format('YYYYWW'));
                startDate.add(1, 'week');
            }
    
            if (weeks.length > 12) { // 12周大约是3个月
                console.log("查询时间跨度不能超过12周");
                ctx.body = response.fail(`${ctx.params.table} 查询时间跨度不能超过12周`);
                return;
            } else if (weeks.length > 1) {
                ctx.params.table = weeks.map(item => `orderInfo_${item}`);
            } else {
                ctx.params.table = `orderInfo_${weeks[0]}`;
            }
        }
    }
    if (body.areaArr == []) {
        body.areaArr = null;
    }
    if (body.orderBy == "endTime") { body.orderBy = ""; body.direction = ""; }

    let res = await db.findAll(ctx.params.table, body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr, body.likeArr, body.leftJoinArr, body.inArr);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} getList error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} getList error :` + res.message);
        return;
    }
    if (res.count) {
        console.log('批量查询结果:', res.count);
        ctx.body = response.success({ rows: res.rows, count: res.count });
    }
    else {
        ctx.body = response.success(res);
    }

});



export { router };